<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="版本号" prop="version">
        <el-input
          v-model="queryParams.version"
          placeholder="请输入版本号"
          clearable
        />
      </el-form-item>
      <el-form-item label="项目" prop="projectId">
        <el-select 
          clearable=""
          v-model="queryParams.projectId" 
          filterable 
          placeholder="请选择"
          >
          <el-option
            v-for="item in project_list"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发布方式" prop="isGrayscale">
        <el-select 
          clearable=""
          v-model="queryParams.isGrayscale" 
          filterable 
          placeholder="请选择"
          >
          <el-option v-for="dict in dict.type.upgrade_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceModelClassify">
        <el-select 
          clearable=""
          v-model="queryParams.deviceModelClassify" 
          filterable 
          placeholder="请选择"
          @change="handleQueryClassifyChange"
          >
          <el-option
            v-for="item in device_classify_list"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备型号" prop="deviceModelCode">
        <el-select 
          clearable=""
          v-model="queryParams.deviceModelCode" 
          filterable 
          placeholder="请选择"
          >
          <el-option
            v-for="item in device_model_list_queryParam"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['produce:produce-plan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['produce:produce-plan:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['produce:produce-plan:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getDeviceUpgradesList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceUpgradesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column sortable label="id" align="center" prop="id" />
      <el-table-column label="包名" align="center" prop="name" sortable/>
      <el-table-column label="版本号" align="center" prop="version" sortable />
      <el-table-column label="设备类型" align="center" prop="deviceModelClassify" sortable>
        <template slot-scope="scope">
          {{ device_classify_list[scope.row.deviceModelClassify].label}}
        </template>
      </el-table-column>
      <el-table-column label="设备型号" align="center" prop="deviceModelName" />
      <el-table-column label="发布方式" align="center" prop="isGrayscale" sortable>
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isGrayscale === 0 " type="success">全量</el-tag>
          <el-tag v-else type="warning">灰度</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="升级设备" align="center" prop="showdeviceList" >
        <template slot-scope="scope">
            <el-select placeholder="点击查询关联产品列表" style="width:100%;" v-model="scope.row.showdeviceList[0]" >
                <el-option  v-for="item in scope.row.showdeviceList" :key="item" :label="item" :value="item" />
            </el-select>
        </template>
      </el-table-column>
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column label="端口" align="center" prop="port">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.port_type" :value="scope.row.port"/>
        </template>
      </el-table-column>
      <el-table-column label="项目" align="center" prop="projectName" sortable>
        <template slot-scope = "scope">
          <div v-for="(item,index) in scope.row.projectName.split(',')" :key="index" >
            <div>
              <!-- <div style="float: left;color:#1910FC">项目{{index+1}}:</div> -->
              <div style="float: left;">项目{{index+1}}:{{ item }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" sortable/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getDeviceUpgradesList"
    />

    <!-- 添加或修改设备升级对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="升级包名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入包名"  maxlength="120" show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="版本号" prop="version">
              <el-input v-model="form.version" placeholder="请输入版本号" type="number" oninput="if(value.length > 6)value =value.slice(0,6)" maxlength="6" show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目" prop="projectId">
              <el-select 
                clearable=""
                @change="handleProjectChange"
                v-model="form.projectId" 
                filterable
                placeholder="请选择项目"
                style="width:240px"
                >
                <el-option
                  v-for="item in project_list"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布方式" prop="isGrayscale">
              <el-select 
                @change="handleIsGrayscaleChange"
                style="width:240px"
                clearable=""
                v-model="form.isGrayscale" 
                filterable 
                placeholder="请选择发布方式"
                >
                <el-option v-for="dict in dict.type.upgrade_type" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备" prop="grayscaleDeviceList">
              <div style="text-decoration: underline #1910FC;color:#1910FC" @click="handleShowDevice">{{ this.deviceNum}}</div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="deviceModelClassify">
              <el-select 
                clearable=""
                v-model="form.deviceModelClassify" 
                filterable 
                placeholder="请选择设备类型"
                style="width:240px"
                @change="handleFormClassifyChange"
                >
                <el-option
                  v-for="item in device_classify_list"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备型号编号" prop="deviceModelCode">
              <el-select 
                clearable=""
                v-model="form.deviceModelCode" 
                filterable 
                placeholder="请选择设备型号编号"
                style="width:240px"
                @change="handleDeviceModelCodeChange"
                >
                <el-option
                  v-for="item in device_model_list_form"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="this.form.deviceModelClassify !== 0">
          <el-col :span="12">
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入地址"  maxlength="2" show-word-limit/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="端口" prop="port">
              <!-- <el-input v-model="form.port" placeholder="请输入端口"  maxlength="1" show-word-limit/> -->
            <el-select 
                clearable=""
                v-model="form.port" 
                filterable 
                placeholder="请选择端口"
                style="width:240px"
                >
                <el-option v-for="dict in dict.type.port_type" :key="dict.value" :label="dict.label"
                :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="升级包" prop="url">
              <div class="upload-file">
                <el-upload
                  multiple
                  :action="uploadFileUrl + '?fileTypeCode=2'"
                  :before-upload="handleBeforeUpload"
                  :file-list="fileList"
                  :limit="limit"
                  :on-error="handleUploadError"
                  :on-exceed="handleExceed"
                  :on-success="handleUploadSuccess"
                  :show-file-list="false"
                  :headers="headers"
                  class="upload-file-uploader"
                  ref="fileUpload"
                >
                  <!-- 上传按钮 -->
                  <el-button size="mini" type="primary">选取文件</el-button>
                  <!-- 上传提示 -->
                  <!-- <div class="el-upload__tip" slot="tip" v-if="showTip">
                    请上传
                    <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
                    <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
                    的文件
                  </div> -->
                </el-upload>
            
                <!-- 文件列表 -->
                <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
                  <li :key="file.url" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList" style="width: 600px">
                    <el-link :href="file.url" :underline="false" target="_blank">
                      <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
                    </el-link>
                    <div class="ele-upload-list__item-content-action">
                      <el-link :underline="false" @click="handleDeleteFile(index)" type="danger">删除</el-link>
                    </div>
                  </li>
                </transition-group>
              </div>
              <!-- <file-upload-oss v-model="form.url" :fileTypeCode="2" placeholder="请上传升级软件包" /> -->
              <!-- <el-input v-model="form.address" placeholder="请输入地址"  maxlength="1" show-word-limit/> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="md5" prop="fileMd5">
              <el-input v-model="form.fileMd5" placeholder="请输入文件md5运算结果"  show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="固件包大小(字节)" prop="fileSize">
              <el-input v-model="form.fileSize" show-word-limit disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="跨版本" prop="spanVersionCode">
              <el-select 
                clearable=""
                v-model="form.spanVersionCode" 
                filterable 
                allow-create 
                default-first-option
                placeholder="请选择能够跨域的版本"
                style="width:240px"
                multiple=""
                @change="spanVersionCodeChange"
                >
                <el-option
                  v-for="item in spanVersionCode_list"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="24">
            <el-form-item label="remark" prop="remark">
              <el-input v-model="form.remark" placeholder="请备注"/>
            </el-form-item>
          </el-col>
        </el-row>
        
        
      </el-form>        

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>

    <!-- 查看需要升级的设备列表 -->
    <el-dialog :title="deviceDialogTitle" :visible.sync="deviceDialogOpen" width="1400px" append-to-body>
      <el-form :model="deviceTableDataQueryParams" ref="deviceQueryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="设备唯一id" prop="deviceId">
          <el-input
            v-model="deviceTableDataQueryParams.deviceId"
            placeholder="请输入设备唯一id"
            clearable
          />
        </el-form-item>
        <el-form-item label="设备名称" prop="name">
          <el-input
            v-model="deviceTableDataQueryParams.name"
            placeholder="请输入设备名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="生命周期" prop="factoryStatus">
          <el-select 
          clearable=""
          v-model="deviceTableDataQueryParams.factoryStatus" 
          filterable 
          placeholder="请选择"
          >
          <el-option v-for="dict in dict.type.factory_status" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDeviceQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetDeviceQuery">重置</el-button>
      </el-form-item>
    </el-form>
      <el-table  v-loading="deviceListLoading" ref="deviceDataTable" :data="deviceList" @selection-change="handleDeviceSelection"  row-key="deviceId">
        <el-table-column type="selection" v-if="unShowSelect" width="55" align="center" :reserve-selection="true"/>
        <el-table-column label="设备唯一id" align="center" prop="deviceId" :show-overflow-tooltip="true" />
        <el-table-column label="设备名称" align="center" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="项目" align="center" prop="projectName" :show-overflow-tooltip="true" />
        <el-table-column label="设备组合" align="center" prop="deviceComposeName" :show-overflow-tooltip="true" />
        <el-table-column label="柜子类型" align="center" prop="containerTypeName" :show-overflow-tooltip="true" />
        <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
        <el-table-column label="生命周期" align="center" prop="factoryStatus" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{ dict.type.factory_status[scope.row.factoryStatus].label }}
          </template>                        
        </el-table-column>
        <el-table-column label="用户" align="center" prop="belongUser" :show-overflow-tooltip="true" />
      </el-table>
      
      <pagination
        v-show="deviceTableDataQueryParams.total>0"
        :total="deviceTableDataQueryParams.total"
        :page.sync="deviceTableDataQueryParams.pageNum"

        :limit.sync="deviceTableDataQueryParams.pageSize"
        @pagination="getProjectDevice"
      />
              <!-- :page-sizes="[5,10,20]" -->
      <!-- <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitChoose">确 定</el-button>
        <el-button @click="cancelChoose">取 消</el-button>
      </div> -->
    </el-dialog>
  </div>
</template>

<script>

import { listDeviceUpgrades, getDeviceUpgradesDetail, addDeviceUpgrades, updateDeviceUpgrades, delDeviceUpgrades } from "@/api/device/deviceUpgrades";
import { listDeviceModel } from "@/api/device/deviceModel";
import { listProject } from "@/api/project/project";
import { listMainDevice } from "@/api/device/mainDevice";
import { getToken } from "@/utils/auth";
import  SparkMD5 from 'spark-md5';
export default {
  dicts: ['port_type','upgrade_type','factory_status'],
  name: "deviceUpgrade",
  props: {
    //code:1 文本  2-软件包 3-图片 4-视频 9999-其他
    fileTypeCode : "",
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 1,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 1024,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "xls", "ppt", "txt", "pdf",'png', 'jpg', 'jpeg','tgz','bin','json','exe','pak','xlsx','csv','xlsm'],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      spanVersionCode:null,
      deviceNum:0,
      number: 0,
      uploadList: [],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/file/oss-controller/upload-file", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      spanVersionCode_list: [],
      fileList: [],
      // 项目ids
      projectIds: '',
      // 是否回显
      reserve:false,
      // 是否展示选择
      unShowSelect:false,
      // 选中的设备ids
      deviceIds:[],
      // 设备表格数据查询参数
      deviceTableDataQueryParams:{
        total: 0,
        pageNum: 1,
        pageSize: 20,
        projectId:'',
        deviceId:'',
        name:'',
        factoryStatus:'',
        orderByColumn:'id',
        isAsc:'desc'
      },
      // 设备表格数据加载
      deviceListLoading:false,
      // 设备表格数据
      deviceList:[],
      // 设备弹框
      deviceDialogOpen:false,
      // 设备弹框名称
      deviceDialogTitle:'',
      // 设备型号列表-检索
      device_model_list_queryParam:[],
      // 设备型号列表-新增
      device_model_list_form:[],
      // 项目列表
      project_list:[],
      // 发布方式
      // package_pub_way_list:[
      //   {value:0,label:'全量发布'},
      //   {value:1,label:'灰度发布'},
      // ],
      // 设备类型列表
      device_classify_list : [
        {value:0,label:'主控'},
        {value:1,label:'温控器'},
        {value:2,label:'网口排面相机'},
        {value:3,label:'485排面相机'}
      ],
      // 设备表单数据
      deviceQueryForm:{
        deviceId:null,
        name:null,
        factoryStatus:null, //出厂状态
      },
      // 表单数据
      form : {
        address: null, // 地址
        port: null, //端口
        deviceModelClassify:null, // 设备类型
        deviceModelCode: null, // 设备型号code
        fileMd5: null, // 文件md5运算结果
        grayscaleDeviceList: [], //灰度设备列表
        isGrayscale	: null, //发布方式 0：不灰度 1：灰度
        name: null, // 升级包名称
        projectId:null, // 项目id
        url:null, // 文件地址
        version:null, // 版本号
        remark:null //备注
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中项目名数组
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备更新表格数据
      deviceUpgradesList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        version: null, //版本号
        projectId: null, //项目id
        isGrayscale: null, //是否灰度发布 0：全量 1：灰度
        deviceModelClassify:null, //设备类型
        deviceModelCode:null, //设备型号
        remark: null, //备注
        orderByColumn:'id',
        isAsc:'desc'
      },
      // 表单校验
      rules: {
        projectId: [
          { required: true, message: "请选择项目", trigger: "blur" }
        ],
        isGrayscale: [
          { required: true, message: "发布方式不能为空", trigger: "blur" }
        ],
        version: [
          { required: true, message: "版本号不能为空", trigger: "blur" },
          {
            message: '长度为5~6，且非0开头的纯数字',
            trigger: 'change',
            pattern:/^[1-9]\d{4,5}$/
          }
        ],
        name: [
          { required: true, message: "升级包名称不能为空", trigger: "blur" }
        ],
        deviceModelClassify: [
          { required: true, message: "设备类型不能为空", trigger: "blur" }
        ],
        deviceModelCode: [
          { required: true, message: "设备型号编号不能为空", trigger: "blur" }
        ],
        url: [
          { required: true, message: "请上传升级包", trigger: "blur" }
        ],
        fileMd5: [
          { required: true, message: "请输入文件md5运算结果", trigger: "blur" }
        ],
        spanVersionCode: [
          { required: true, message: "请选择需要跨越的版本号", trigger: "blur" }
        ],
      }
    };
  },
  watch: {
    
    'form.projectId': function (val, old) {
      if (this.form.projectId  && this.form.isGrayscale == '0') {
        if(this.form.projectId){
          this.projectIds = this.form.projectId + ',';
        }
        const params={
          projectIds:this.projectIds
        }
        listMainDevice(params).then((res) =>{
          this.form.grayscaleDeviceList = []
          if(res.code === 200){
              if(res.rows.length>0){
                for(var i=0;i<res.rows.length;i++){
                  this.form.grayscaleDeviceList.push(res.rows[i].deviceId)
                }
              }else{
                this.$message.warning("当前选择的项目下无设备，请先为项目添加设备")
              }
          }
        }).catch((err) =>{
          this.$message.error("设备列表获取失败，原因："+err.message)
        }).finally(() =>{
          
        })
      }
    },
    value: {
      handler(val) {
        if (val) {
          let temp = 1;
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(',');
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === "string") {
              item = { name: item, url: item };
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getDeviceUpgradesList();
    this.getProjectList();
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    // 点击跨版本
    spanVersionCodeChange(){
      this.$forceUpdate();
      console.log("强制刷新")
    },
    // 项目改变
    handleProjectChange(){
      this.form.isGrayscale = null;
      this.form.grayscaleDeviceList = [];
      this.deviceNum = 0;
      this.form.deviceModelClassify = null;
      this.form.deviceModelCode = null;
      this.spanVersionCode = [];
      this.device_model_list_form = [];
    },
    // 设备型号编号改变
    handleDeviceModelCodeChange(){
      // 获取版本列表
      this.getSpanVersionCodeList();
    },
    // 文件url转file
    async fetchFileFormUrl(fileUrl){
      const response = await fetch(fileUrl);
      if(!response.ok){
        throw new Error("Network response was not ok"+response.statusText);
      }
      const blob = await response.blob();
      const fileName = fileUrl.split('/').pop();
      const file = new File([blob], fileName, {type: blob.type});
      return file;
    },
    // 发布方式改变
    handleIsGrayscaleChange(){
      // this.form.grayscaleDeviceList = []
      if (this.form.projectId && this.form.isGrayscale == '0') {
        if(this.form.projectId){
          this.projectIds = this.form.projectId + ',';
        }
        const params={
          projectIds:this.projectIds
        }
        listMainDevice(params).then((res) =>{
          this.form.grayscaleDeviceList = []
          if(res.code === 200){
              if(res.rows.length>0){
                for(var i=0;i<res.rows.length;i++){
                  this.form.grayscaleDeviceList.push(res.rows[i].deviceId)
                }
                this.deviceNum = this.form.grayscaleDeviceList.length;
                this.$forceUpdate();
              }else{
                this.$message.warning("当前选择的项目下无设备，请先为项目添加设备")
              }
          }
        }).catch((err) =>{
          this.$message.error("设备列表获取失败，原因："+err.message)
        }).finally(() =>{
          
        })
      }
      else if (this.form.isGrayscale == '1'){
        this.form.grayscaleDeviceList =[]
        this.deviceNum = 0;
        this.$forceUpdate();
      }
    },
    // 获取全部版本列表
    getSpanVersionCodeList(){   
      const params = {
        pageNum: 1,
        pageSize: 1000,
        deviceModelClassify:this.form.deviceModelClassify,
        projectId:this.form.projectId+',',
        deviceModelCode:this.form.deviceModelCode
      }
      listDeviceUpgrades(params).then((res) =>{
        const rows = res.rows.map((item) =>{
          if(item.version !== this.form.version){
            return {
              label: item.version,
              value: item.version.toString()
            }
          }

        }).filter((v) => v)
        this.spanVersionCode_list = rows
        if(this.spanVersionCode){
          this.form.spanVersionCode = this.spanVersionCode
        }
      })
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件大小
      return new Promise((resolve, reject) => {
        // 校检文件类型
        if (this.fileType) {
          const fileName = file.name.split('.');
          const fileExt = fileName[fileName.length - 1];
          const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
          if (!isTypeOk) {
            this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
            return false;
          }
        }
        // 校检文件大小
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
        this.form.fileSize = file.size / 8
        // console.log("文件大小为（b）",file.size)
        // console.log("文件大小为（字节）",file.size / 8)
        this.form.url = ''
        const fileReader = new FileReader()
        // fileReader.readAsBinaryString(file)
        fileReader.onload = (e) => {
          const fileContent = e.target.result;
          const spark = new SparkMD5.ArrayBuffer();
          spark.append(fileContent);
          const md5 = spark.end();
          this.form.fileMd5 = md5
          resolve(file)
        }
        fileReader.readAsArrayBuffer(file);
        fileReader.onerror = (err) => {
          this.$message.error('生成 MD5 失败')
          reject(file)
        }
        this.$modal.loading("正在上传文件，请稍候...");
        this.number++;
        return true;
      })
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading()
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.form.url = res.data.url;
        this.form.fileSize = file.size/8 ; // file.size为bit 转换为字节/8
        this.uploadList.push({ name: res.data.url, url: res.data.url });
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 删除文件
    handleDeleteFile(index) {
      this.fileList.splice(index, 1);
      this.$emit("input", this.listToString(this.fileList));
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        this.$modal.closeLoading();
      }
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return decodeURIComponent(name.slice(name.lastIndexOf("/") + 1)).slice(32);
      } else {
        return "";
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    },
    /** 重置设备表格检索条件 */
    resetDeviceQuery(){
      this.resetForm("deviceQueryForm");
      this.getDeviceList()
    },
    /** 获取设备列表 */
    getDeviceList(){
        // 获取项目下的设备
        const params={
          projectIds:this.projectIds,
          ...this.deviceTableDataQueryParams
        }
        listMainDevice(params).then((res) =>{
          this.deviceList = res.rows
        })
    },
    /** 设备搜索按钮操作 */
    handleDeviceQuery(){
      this.deviceTableDataQueryParams.pageNum = 1
      this.getDeviceList()
    },
    /** 设备表格数据多选 */
    handleDeviceSelection(selection){
      if(selection.length === 0){
        this.form.grayscaleDeviceList = []
        this.deviceNum = 0;
        this.$forceUpdate();
      }else{
        // this.form.grayscaleDeviceList = selection
        this.form.grayscaleDeviceList = selection.map((item) =>{
          return item.deviceId
        }).filter((v) => v)
        this.deviceNum = this.form.grayscaleDeviceList.length;
        this.$forceUpdate();
      }
    },
    /** 点击设备数量触发事件 type0：全量 type1：灰度*/
    getProjectDevice(type){
        this.deviceListLoading = true
        if(this.form.projectId){
          this.projectIds = this.form.projectId + ',';
        }
        // 获取项目下的设备
        const params={
          projectIds:this.projectIds,
          ...this.deviceTableDataQueryParams
        }
        listMainDevice(params).then((res) =>{
          if(res.code === 200){
              if(res.rows.length > 0){
                this.deviceList = res.rows

                this.deviceDialogTitle = '选择需要升级的设备'
                // this.deviceTableDataQueryParams.pageSize = 5
                // this.deviceTableDataQueryParams.pageNum = 1
                this.deviceTableDataQueryParams.total = res.total
                this.deviceDialogOpen = true
                if(type === 0){   //全量 即 项目下所有设备都是需要升级的
                  //todos 全选

                }else{ //灰度 如果this.form.grayscaleDeviceList=0 则展示deviceList，如果大于0 则展示deviceList并回显grayscaleDeviceList的数据
                  if(this.form.grayscaleDeviceList.length>0 && this.title == '添加设备升级'){
                    let selectionList = [] //定义一个数组用于存放需要回显的行数据
                    for(var i=0;i<this.form.grayscaleDeviceList.length;i++){ //循环之前选中的和获取的设备列表数据
                      for(var j=0;j<this.deviceList.length;j++){
                        if(this.form.grayscaleDeviceList[i] == this.deviceList[j].deviceId){//进行对比，是则存入回显的数组中
                          if(selectionList.indexOf(this.deviceList[j]) === -1){
                            selectionList.push(this.deviceList[j])
                          }

                        }
                      }
                    }
                    this.$nextTick(_ =>{
                      this.$refs.deviceDataTable.clearSelection();
                      selectionList.forEach((row) => {//循环执行选中方法，进行回显
                        // this.handleDeviceSelection(row)
                        this.$refs.deviceDataTable.toggleRowSelection(row,true)
                      })
                    })

                  }
                  if(this.form.grayscaleDeviceList.length === 0){


                    this.$nextTick(_ =>{
                      this.$refs.deviceDataTable.clearSelection();
                    })
                  }


                  if(this.form.grayscaleDeviceList.length>0 && this.title == '修改设备升级'){
                    let selectionList = [] //定义一个数组用于存放需要回显的行数据
                    for(var i=0;i<this.form.grayscaleDeviceList.length;i++){ //循环之前选中的和获取的设备列表数据
                      for(var j=0;j<this.deviceList.length;j++){
                        if(this.form.grayscaleDeviceList[i] == this.deviceList[j].deviceId){//进行对比，是则存入回显的数组中
                          if(selectionList.indexOf(this.deviceList[j]) === -1){
                            selectionList.push(this.deviceList[j])
                          }

                        }
                      }
                    }
                    // this.$refs.deviceDataTable.clearSelection()
                    // 清空所有选中状态
                    this.$nextTick(_ =>{
                      this.$refs.deviceDataTable.clearSelection();
                      selectionList.forEach((row) => {//循环执行选中方法，进行回显
                        // this.handleDeviceSelection(row)
                        this.$refs.deviceDataTable.toggleRowSelection(row,true)
                      })
                    })
                  }
                }
                
              }else{
                this.$message.warning("当前选择的项目下无设备，请先为项目添加设备")
              }
          } 
        }).catch((err) =>{
          this.$message.error("设备列表获取失败，原因："+err.message)
        }).finally(() =>{
          this.deviceListLoading=false
        })
    },
    /** 展示设备列表 */
    handleShowDevice(){
      // if(this.title == "添加设备升级"){
        // 灰度 全量发布
        if(this.form.isGrayscale == '0' ){
          this.unShowSelect = false
          // 全量发布
          this.getProjectDevice(0)
        }else if(this.form.isGrayscale == '1'){
          this.unShowSelect = true
          // 配置表格数据是否回显
          console.log("是否回显",this.deviceNum.length === 0 ? '不回显' : '回显')
          // 灰度发布
          this.getProjectDevice(1)
        }else{
          this.$message.warning("请先选择发布方式和项目")
        }
      // }else{
      //   //修改
      // }

    },
    /** 设备类型变化 */
    handleQueryClassifyChange(){
      this.queryParams.deviceModelCode = null
      this.device_model_list_queryParam = []
      const params={
        type:this.queryParams.deviceModelClassify === 0 ? 1 : 2,
        classify:this.queryParams.deviceModelClassify
      }
      listDeviceModel(params).then((res) =>{
        if(res.code === 200 && res.rows.length > 0){
          this.device_model_list_queryParam = res.rows.map((item) =>{
            return {value:item.id,label:item.name}
          })
        }
      })
    },
    /** 设备类型变化 */
    handleFormClassifyChange(){
      this.form.deviceModelCode = null
      this.device_model_list_form = []
      const params={
        type:this.form.deviceModelClassify === 0 ? 1 : 2,
        classify:this.form.deviceModelClassify
      }
      listDeviceModel(params).then((res) =>{
        if(res.code === 200 && res.rows.length > 0){
          this.device_model_list_form = res.rows.map((item) =>{
            return {value:item.code,label:item.name}
          })
        }
      })
    },
    /** 获取项目列表 */
    getProjectList(){
      listProject().then((res) =>{
        if(res.code === 200 && res.rows){
          this.project_list = res.rows.map((item) =>{
            return {label:item.projectName,value:item.id.toString()}
          })
        }
      }).catch((err) =>{
        this.$message.error("项目列表获取失败，原因："+err.message)
      }).finally(() =>{

      })
    },
    /** 获取设备更新列表 */
    getDeviceUpgradesList(){
      this.loading = true;
      //给项目id最后加个逗号
      const params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        version: this.queryParams.version, //版本号
        projectId: this.queryParams.projectId ? this.queryParams.projectId + ',' : null, //项目id
        isGrayscale: this.queryParams.isGrayscale, //是否灰度发布 0：不灰度 1：灰度
        deviceModelClassify:this.queryParams.deviceModelClassify, //设备类型
        deviceModelCode:this.queryParams.deviceModelCode, //设备型号
        remark: this.queryParams.remark, //备注
        orderByColumn:'id',
        isAsc:'desc'
      }
      listDeviceUpgrades(params).then((res) =>{
        if(res.code === 200){
          this.deviceUpgradesList = res.rows;

          for(var i=0;i<this.deviceUpgradesList.length;i++){
            if(this.deviceUpgradesList[i].grayscaleDeviceList){
              this.deviceUpgradesList[i].showdeviceList = this.deviceUpgradesList[i].grayscaleDeviceList.split(',')
              this.deviceUpgradesList[i].showdeviceList.pop()
            }else{
              this.deviceUpgradesList[i].showdeviceList = []
            }
          }
          this.total = res.total
        }
      }).catch((err) =>{
        this.$message.error("设备更新获取失败，原因："+err.message)
      }).finally(() =>{
        this.loading = false;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        address: null, // 地址
        port: null, //端口
        deviceModelClassify:null, // 设备类型
        deviceModelCode: null, // 设备型号code
        fileMd5: null, // 文件md5运算结果
        grayscaleDeviceList: [], //灰度设备列表
        isGrayscale	: null, //发布方式 0：全量 1：灰度
        name: null, // 升级包名称
        projectId:null, // 项目id
        url:null, // 文件地址
        version:null // 版本号
      },
      this.deviceNum = 0;
      this.fileList = [];
      this.spanVersionCode = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getDeviceUpgradesList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.names = selection.map(item => item.model)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备升级";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDeviceUpgradesDetail(id).then(response => {
        this.form = response.data;
        const deviceModelCode = this.form.deviceModelCode;
        //数据处理
        this.form.isGrayscale = this.form.isGrayscale.toString();
        if(this.form.port){
          this.form.port = this.form.port.toString();
        }
        if(this.form.grayscaleDeviceList){
          this.form.grayscaleDeviceList = this.form.grayscaleDeviceList.split(',');
          this.form.grayscaleDeviceList.pop();
          this.deviceNum = this.form.grayscaleDeviceList.length 
        }
        if(this.form.spanVersionCode){
          this.form.spanVersionCode = this.form.spanVersionCode.split(',');
          this.form.spanVersionCode.pop();
        }
        if(this.form.projectId){
          this.form.projectId = this.form.projectId.split(',')[0];
        }
        this.projectIds = this.form.projectId;
        this.fetchFileFormUrl(this.form.url)
        .then(file =>{
          this.fileList = [{
            name: this.form.url,
            url: this.form.url
          }];
          this.$forceUpdate();
        })
        .catch(err =>{
          console.log(err)
        })
        this.spanVersionCode = this.form.spanVersionCode;
        // this.form.projectId = this.form.projectId.split(',');
        this.$forceUpdate();
        this.handleFormClassifyChange();
        this.form.deviceModelCode = deviceModelCode;
        this.getSpanVersionCodeList();
        this.open = true;
        this.title = "修改设备升级";
      });
    },
    /** 提交按钮 */
    submitForm(){
      this.$refs["form"].validate(valid => {
        let deviceIdList = this.form.grayscaleDeviceList.map((item) =>{
          return item
        }).filter((v) => v)
        // 给版本号排序
        let spanVersionCodeString = ''
        if(this.form.spanVersionCode){
          this.form.spanVersionCode.sort((a,b) => a-b);
          if(this.form.spanVersionCode.length>0){
            spanVersionCodeString = ((this.form.spanVersionCode.length > 1) ? ( this.form.spanVersionCode.join(',') + ',') : (this.form.spanVersionCode[0] + ','));
          }
        }
        if(deviceIdList.length > 0){
          deviceIdList = ((deviceIdList.length > 1) ? ( deviceIdList.join(',') + ',') : (deviceIdList[0] + ','));
        }else{
          deviceIdList = null
        }
        let projectIds = ''
        if(this.form.projectId){
          projectIds = this.form.projectId + ',';
        }
        let params = {
          id:this.form.id,
          address: this.form.address, // 地址
          port: this.form.port ? parseInt(this.form.port) : null, //端口
          deviceModelClassify:this.form.deviceModelClassify, // 设备类型
          deviceModelCode: this.form.deviceModelCode, // 设备型号code
          fileMd5: this.form.fileMd5, // 文件md5运算结果
          grayscaleDeviceList: deviceIdList, //灰度设备列表
          isGrayscale	: parseInt(this.form.isGrayscale), //发布方式 0：不灰度 1：灰度
          name: this.form.name, // 升级包名称
          projectId:projectIds, // 项目id
          url:this.form.url, // 文件地址
          version:this.form.version, // 版本号
          fileSize:this.form.fileSize,  
          spanVersionCode:spanVersionCodeString
        }
        if (valid) {
          if (this.form.id != null) {
            updateDeviceUpgrades(params).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getDeviceUpgradesList();
            });
          } else {
            addDeviceUpgrades(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getDeviceUpgradesList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      //todos 修改
      const ids = row.id || this.ids;
      const names = row.model || this.names
      this.$modal.confirm('是否确认删除升级包名为"' + names + '"的数据项？').then(function() {
          // 修改为逻辑删除
        return delDeviceUpgrades(ids);
      }).then(() => {
        this.getDeviceUpgradesList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/genius/platform-device-upgrades/export', {
        ...this.queryParams
      }, `设备升级列表_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss">
.fullRelease{
  color: #32CD1D;
  font-size: 18px;
}
.grayScaleRelease{
  color: #1A3CDF;
  font-size: 18px;

}
.formTitle{
  width:100%;
  text-align:center;
  margin:15px 0 15px 0;
  font-weight:border;
  font-size:20px
}
</style>
